from datetime import timedelta
from typing import Any, Dict

from fastapi import APIRouter, Body, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from app.core.config import settings
from app.core.security import create_access_token, refresh_token, get_current_active_user
from app.db.session import get_db
from app.crud.user import user
from app.models.user import SysUsers
from app.schemas.token import Token, TokenResponse
from app.utils.response import success_response, error_response

router = APIRouter()


@router.post("/auth/login", response_model=TokenResponse)
def login_access_token(
    db: Session = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
) -> Dict[str, Any]:
    """
    获取OAuth2兼容的令牌，用于用户认证
    """
    user_obj = user.authenticate(db, username=form_data.username, password=form_data.password)
    if not user_obj:
        return error_response(code=400, message="用户名或密码不正确")
    elif not user.is_active(user_obj):
        return error_response(code=400, message="用户已被禁用")
    
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    token = create_access_token(
        subject=user_obj.id, expires_delta=access_token_expires
    )
    
    token_data = {
        "access_token": token,
        "token_type": "bearer"
    }
    
    return success_response(data=token_data, message="登录成功")


@router.post("/auth/refresh-token", response_model=TokenResponse)
def refresh_access_token(
    current_token: dict = Depends(refresh_token),
) -> Dict[str, Any]:
    """
    刷新访问令牌
    """
    return success_response(data=current_token, message="令牌刷新成功")


@router.post("/auth/logout")
def logout(
    current_user: SysUsers = Depends(get_current_active_user),
) -> Dict[str, Any]:
    """
    用户退出登录
    """
    # 在实际项目中，这里可以添加令牌黑名单或其他退出逻辑
    # 由于JWT是无状态的，所以实际登出操作通常在前端完成（清除本地令牌）
    return success_response(data={"logout": True}, message="退出登录成功")